# -*- coding: utf-8 -*-
from __future__ import unicode_literals

import hashlib
import json
import os
import urllib2

# import redis
from django.http import JsonResponse
from config import const
from libs.WXBizDataCrypt import WXBizDataCrypt


# Create your views here.
# pool = redis.ConnectionPool(host='127.0.0.1', port=6379)
# redis_help = redis.Redis(connection_pool=pool)


def authUser(request):
    '''
        验证用户，根据传入code，获取用户session_key,openid
    '''
    code = request.GET.get('code', '')
    if code:
        # 向服务器验证，获取用户session_key和openid
        # code = "013LQsMz09Oqtg1MRJNz04SuMz0LQsMm"
        url = 'https://api.weixin.qq.com/sns/jscode2session'
        params1 = {"grant_type": 'authorization_code', "appid": 'wx8292320488d40a87',
                   "secret": '0d677e7b2633583a35fef9b74c57e65a', "js_code": code},
        url = url + "?grant_type=authorization_code&appid=wx8292320488d40a87&secret=0d677e7b2633583a35fef9b74c57e65a&js_code=" + code
        print url
        request = urllib2.Request(url)
        res_data = urllib2.urlopen(request)
        res = json.loads(res_data.read())
        session_key = res.get('session_key', '')
        openid = res.get('openid', '')
        # 生成本地sessionid，在redis服务器中保留用户敏感信息
        sessionid = hashlib.sha1(os.urandom(24)).hexdigest()
        print session_key
        # redis_help.set(sessionid, "%s||%s" % (session_key, openid), ex=const.APP_EXPIRY)
        return JsonResponse({"sessionid": sessionid})
    else:
        return JsonResponse({"data": "non code value."})


def getUserPhone(request):
    '''
        获取用户手机号码
    '''
    sessionid = request.GET.get('sessionid', '')
    encrypteddata = request.GET.get('encrypteddata', '')
    iv = request.GET.get('iv', '')
    if sessionid:
        # 根据id取得缓存中保存用户session_key,openid
        # sessiondata = redis_help.get(sessionid)
        sessiondata = ""
        if sessiondata:
            # 处理sessiondata
            authdata = sessiondata.split('||')
            decrypteddata = decryptData(authdata[0], encrypteddata, iv)
            return JsonResponse({"phoneNumber": decrypteddata["purePhoneNumber"]})


def decryptData(sessionkey, encrypteddata, iv):
    appId = const.APP_ID
    # sessionKey = "Lfsgm/Qh7Djrlh7YsJc9Ww=="
    # encryptedData = 'LfwDFWZu797aLQZgWS0IG1E+uG8QdXrAQsMg6l9auIfqAdXHTE+aTjWcZT/FckZmpPbUY+gJotzQ+H8q+uk9V9ZVNBRtdXSk3l/L/CDAFMRrBW54qEmFyRhmOYLmOihre/QubbWLqTmPEGH1mzAumR6MIGnv8FHs5X9f2RvczaoZgSuvAVrDUwTsMglZsrPKD+JP1seTUNDosde+a9x8Sp8q7wPU17+LX4lYG5j3StevrrzH3uFgGoszgoKxp6uUgk33+WL4Dwsl0Y7hbaRw4Hbdu1SAwjduF4PcNEDliNml2XhPUbjw3imNYiM7BMwhldlvqs1rZitOGGUEmwX83Cv7u5w9nyfH5OllePjywNdbmsWD5u/RdjWpVY7M42IIFHkjza5LgqzZhO1ILrCeZ8aHeujHMU9L7l14wpPbIub0+P0MoyLR0Z+kl1sbsqcmAlwC7b0mYP+BkPpDu2sfDX6w2Jg2RbqreQPPDDmCn2U='
    # iv = 'NhkGG0LHCPtCLWHy03Paqw=='
    pc = WXBizDataCrypt(appId, sessionkey)
    return pc.decrypt(encrypteddata, iv)

